<?php

namespace app\admin\controller;

use app\BaseController;
use think\exception\HttpException;

class Error extends BaseController
{
    public function __call($method, $args)
    {
        $paths = explode('/',request()->pathinfo());
        if (count($paths) > 2) {
            return $this->loadController($paths, $args);
        }
        throw new HttpException(404, '控制器不存在');
    }

    protected function loadController($paths, $args) {
        $npaths = array_slice($paths,0, count($paths) - 2);
        $controller = $paths[count($paths) - 2];
        if (strpos($controller, '_')) {
            $npaths = array_merge($npaths, explode('_', $controller));
            $paths[count($paths) - 2] = $npaths[count($npaths) - 1];
        }
        foreach ([__NAMESPACE__, 'app\\plug\\controller'] as $controllerDir) {
            $className = $controllerDir;
            foreach ($npaths as $npath) {
                $className .= '\\'.$npath;
            }
            $className .= '\\'.ucfirst($paths[count($paths) - 2]);
            if (class_exists($className)){
                $controller = new $className(app());
                if (is_callable([$controller,$paths[count($paths) - 1]])) {
                    $data =  call_user_func_array([$controller,$paths[count($paths) - 1]], $args);
                    if ($data) {
                        return response($data, 200,['Content-Type: application/json; charset=utf-8'],'json');
                    }else{
                        return;
                    }
                }
                throw new HttpException(404, "方法{$className}->{$paths[count($paths) - 1]}不存在");
            }
        }
        $controller = ucfirst($paths[count($paths) - 2]);
        throw new HttpException(404, "控制器{$controller}不存在");
    }
}